﻿using System;
using System.Windows.Forms;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Yahoo.Yui.Compressor;

namespace JSCSS_Compressor
{
    public partial class CompressorForm : Form
    {
        string configPath = string.Empty;
        string configName = "JSCSS_Compressor.exe.config";

        string FileUrl = string.Empty;
        string DescriptionName = string.Empty;
        string DescriptionVersions = string.Empty;
        string DescriptionUrl = string.Empty;
        string DescriptionEmail = string.Empty;        

        public CompressorForm()
        {
            InitializeComponent();

            //读取配置文件
            configPath = System.Windows.Forms.Application.StartupPath + "\\" + configName;            
            GetConfig();

            filePath.Text = FileUrl;
            textDescriptionName.Text = DescriptionName;
            textDescriptionVersions.Text = DescriptionVersions;
            textDescriptionUrl.Text = DescriptionUrl;
            textDescriptionEmail.Text = DescriptionEmail;
        }

        private void CompressorForm_Load(object sender, EventArgs e)
        {
            try
            {
                listBox.Items.Add("压缩工具加载完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载程序出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 选择压缩文件路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectPath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fs = new FolderBrowserDialog();
            if (DialogResult.OK == fs.ShowDialog())
            {
                filePath.Text = fs.SelectedPath;
                listBox.Items.Add("压缩文件路径：" + filePath.Text);
            }
        }

        #region 保存配置
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            //当程序进来判断Enabled状态,若是false表示上一次未执行完,
            if (!this.btnSaveConfig.Enabled)
            { return; }

            this.btnSaveConfig.Enabled = false;

            FileUrl = filePath.Text;
            string DescriptionName = textDescriptionName.Text;
            string DescriptionVersions = textDescriptionVersions.Text;
            string DescriptionUrl = textDescriptionUrl.Text;
            string DescriptionEmail = textDescriptionEmail.Text;

            //更新配置文件
            SaveConfig("FileUrl", FileUrl.ToString());
            ConfigurationManager.RefreshSection("appSettings");

            SaveConfig("DescriptionName", DescriptionName.ToString());
            ConfigurationManager.RefreshSection("appSettings");

            SaveConfig("DescriptionVersions", DescriptionVersions.ToString());
            ConfigurationManager.RefreshSection("appSettings");

            SaveConfig("DescriptionUrl", DescriptionUrl.ToString());
            ConfigurationManager.RefreshSection("appSettings");

            SaveConfig("DescriptionEmail", DescriptionEmail.ToString());
            ConfigurationManager.RefreshSection("appSettings");

            listBox.Items.Add("更新配置文件完成");

            this.btnSaveConfig.Enabled = true;
        }
        #endregion

        #region 开始压缩
        private void btnCompressor_Click(object sender, EventArgs e)
        {
            //当程序进来判断Enabled状态,若是false表示上一次未执行完,
            if (!this.btnCompressor.Enabled)
            { return; }

            this.btnCompressor.Enabled = false;

            FileUrl = filePath.Text;
            string DescriptionName = textDescriptionName.Text;
            string DescriptionVersions = textDescriptionVersions.Text;
            string DescriptionUrl = textDescriptionUrl.Text;
            string DescriptionEmail = textDescriptionEmail.Text;

            bool isDescription = false;

            if (!string.IsNullOrEmpty(DescriptionName) || !string.IsNullOrEmpty(DescriptionVersions) || !string.IsNullOrEmpty(DescriptionUrl) || !string.IsNullOrEmpty(DescriptionEmail))
            {
                isDescription = true;
            }    

            if (string.IsNullOrEmpty(FileUrl))
            {
                listBox.Items.Add("请选择要压缩的文件路径");
            }
            else
            {
                var files = System.IO.Directory.GetFiles(FileUrl, "*.*", SearchOption.AllDirectories);

                if (files != null && files.Length > 0)
                {
                    listBox.Items.Add("==========开始压缩文件==========");

                    int _jsCount = 0;
                    int _jsSuccessCount = 0;
                    int _cssCount = 0;
                    int _cssSuccessCount = 0;
                    int _ErrorCount = 0;

                    foreach (var file in files)
                    {
                        try
                        {
                            FileInfo finfo = new FileInfo(file);
                            string strContent = File.ReadAllText(file, Encoding.UTF8);

                            //重命名
                            string _min_file = file.Insert(file.LastIndexOf('.'), ".min");

                            //名称不是min
                            if (!file.ToLower().Contains(".min."))
                            {
                                //取消文件只读
                                File.SetAttributes(file, FileAttributes.Normal);

                                if (finfo.Extension.ToLower() == ".js")
                                {
                                    _jsCount++;

                                    //初始化JS压缩类
                                    var js = new JavaScriptCompressor();
                                    js.CompressionType = CompressionType.Standard;//压缩类型
                                    js.Encoding = Encoding.UTF8;//编码
                                    js.IgnoreEval = false;//大小写转换
                                    js.ThreadCulture = System.Globalization.CultureInfo.CurrentCulture;

                                    //压缩该js
                                    strContent = js.Compress(strContent);

                                    //组合说明信息
                                    string strDescription = "";

                                    if (isDescription)
                                    {
                                        strDescription += "/*!" + Environment.NewLine;
                                        strDescription += " * =====================================================" + Environment.NewLine;

                                        if (!string.IsNullOrEmpty(DescriptionName))
                                        {
                                            strDescription += " * " + DescriptionName + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionVersions))
                                        {
                                            strDescription += " * " + DescriptionVersions + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionUrl))
                                        {
                                            strDescription += " * " + DescriptionUrl + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionEmail))
                                        {
                                            strDescription += " * " + DescriptionEmail + Environment.NewLine;
                                        }

                                        strDescription += " * =====================================================" + Environment.NewLine;
                                        strDescription += " */" + Environment.NewLine;
                                    }

                                    strContent = strDescription + strContent;
                                    File.WriteAllText(_min_file, strContent, Encoding.UTF8);

                                    listBox.Items.Add(_min_file + "压缩完成");
                                    _jsSuccessCount++;
                                }
                                else if (finfo.Extension.ToLower() == ".css")
                                {
                                    _cssCount++;

                                    //进行CSS压缩
                                    CssCompressor css = new CssCompressor();
                                    strContent = css.Compress(strContent);

                                    //组合说明信息
                                    string strDescription = "";

                                    if (isDescription)
                                    {
                                        strDescription += "/*!" + Environment.NewLine;
                                        strDescription += " * =====================================================" + Environment.NewLine;

                                        if (!string.IsNullOrEmpty(DescriptionName))
                                        {
                                            strDescription += " * " + DescriptionName + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionVersions))
                                        {
                                            strDescription += " * " + DescriptionVersions + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionUrl))
                                        {
                                            strDescription += " * " + DescriptionUrl + Environment.NewLine;
                                        }

                                        if (!string.IsNullOrEmpty(DescriptionEmail))
                                        {
                                            strDescription += " * " + DescriptionEmail + Environment.NewLine;
                                        }

                                        strDescription += " * =====================================================" + Environment.NewLine;
                                        strDescription += " */" + Environment.NewLine;
                                    }

                                    strContent = strDescription + strContent;
                                    File.WriteAllText(_min_file, strContent, Encoding.UTF8);

                                    listBox.Items.Add(_min_file + "压缩完成");
                                    _cssSuccessCount++;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            listBox.Items.Add("压缩出错：" + ex.Message);
                            _ErrorCount++;
                        }
                    }

                    listBox.Items.Add("==========压缩文件结束==========");
                    listBox.Items.Add(_jsCount + " JS文件，" + _jsSuccessCount + " 压缩成功");
                    listBox.Items.Add(_cssCount + " CSS文件，" + _cssSuccessCount + " 压缩成功");
                    listBox.Items.Add(_ErrorCount + " 压缩失败");
                }
                else
                {
                    listBox.Items.Add("暂无可压缩的文件");
                }
            }

            this.btnCompressor.Enabled = true;
        }
        #endregion

        private void CompressorForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Close();
            System.Environment.Exit(0);
        }

        //Config文件读取
        private void GetConfig()
        {
            if (System.IO.File.Exists(configPath))
            {
                ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
                ecf.ExeConfigFilename = configPath;
                Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
                var keys = config.AppSettings.Settings.AllKeys.ToList();

                listBox.Items.Add("配置文件读取完成");

                if (keys == null || keys.Count == 0)
                {
                    return;
                }

                if (keys.Contains("FileUrl"))
                {
                    FileUrl = config.AppSettings.Settings["FileUrl"].Value.ToString();
                }

                if (keys.Contains("DescriptionName"))
                {
                    DescriptionName = config.AppSettings.Settings["DescriptionName"].Value.ToString();
                }

                if (keys.Contains("DescriptionVersions"))
                {
                    DescriptionVersions = config.AppSettings.Settings["DescriptionVersions"].Value.ToString();
                }

                if (keys.Contains("DescriptionUrl"))
                {
                    DescriptionUrl = config.AppSettings.Settings["DescriptionUrl"].Value.ToString();
                }

                if (keys.Contains("DescriptionEmail"))
                {
                    DescriptionEmail = config.AppSettings.Settings["DescriptionEmail"].Value.ToString();
                }
            }
            else
            {
                listBox.Items.Add("配置文件不存在");
                MessageBox.Show("配置文件不存在，请检查！");
            }
        }

        //Config文件保存
        private void SaveConfig(string key, string value)
        {
            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = configPath;
            Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
            {
                config.AppSettings.Settings[key].Value = value;
            }
            else
            {
                config.AppSettings.Settings.Add(key, value);
            }

            config.Save(ConfigurationSaveMode.Modified);
        }
    }
}
